package com.asset.dispoal.role.service.commom;

import com.asset.dispoal.role.domain.db.entity.GbRoleDo;
import com.asset.dispoal.role.domain.db.mapper.GbRoleMapper;
import com.asset.dispoal.role.dto.GbRoleRequest;
import com.asset.dispoal.role.service.converter.RoleConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.core.util.CollectionUtil;
import tech.mhuang.pacebox.springboot.core.local.GlobalHeaderThreadLocal;
import tech.mhuang.pacebox.springboot.protocol.Result;

/**
 * @author qr
 * @date 2022/3/2$
 */
@Component
public class UpdateRoleCommand implements BaseCommand<GbRoleRequest, Result> {

    @Autowired
    GbRoleMapper roleMapper;

    @Override
    public Result execute(GbRoleRequest request) {
        final GbRoleDo gbRoleDo = RoleConverter.INSTANCE.reqToDo(request);
        String companyId = GlobalHeaderThreadLocal.getOrException().getCompanyId();
        gbRoleDo.setCompanyId(companyId);
        roleMapper.update(gbRoleDo);

        roleMapper.deleteByCommon(gbRoleDo.getId());

        if (CollectionUtil.isNotEmpty(request.getUserIds())) {
            roleMapper.insertAuthUser(gbRoleDo.getId(), request.getUserIds());
        }
        if (CollectionUtil.isNotEmpty(request.getDepartIds())) {
            roleMapper.insertAuthDepart(gbRoleDo.getId(), request.getDepartIds());
        }
        return Result.ok();
    }
}
